//
//  FileListManager.m
//  ICE_Player
//
//  Created by xl on 11-7-25.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include <dirent.h>
#include <sys/stat.h>
#import "FileListManager.h"
#import "FileListView.h"
#import "ICE_global_var.h"
#import "Globalize.h"
#import "BGView.h"
#import "Player_Model.h"

static NSString *p_cell_id = @"FileListCell";

//for file icon
static UIImage* g_icon_array[F_T_NUM] = {0};
static NSString* g_icon_img_path[F_T_NUM] = {@"other.png",@"movie.png",@"audio.png",@"picture.png"};
static BOOL g_is_lock_screen_disabled_before_file_trans = NO;

static BOOL g_is_transloading_file = NO;

static BOOL lock_dir(char* dir, BOOL is_lock);

@interface FileListManager(PrivateMethod)
- (void)Got_Movie_Info_CallBack;
- (void)Load_Movie_Info_To_Low_Wnd:(char*)url file_name:(char*)name;
- (BOOL)is_lock_file;
- (void)On_Finished_Lock;
- (void)Disable_Lock_Screen;
- (void)Resume_Lock_Screen;
@end

@implementation FileListManager

@synthesize p_cell;
@synthesize file_list;
@synthesize cur_dir;
@synthesize p_list_view;

//for wifi transport
@synthesize wifi_transport_begin;
@synthesize wifi_transport_end;
@synthesize wifi_transport_is_doing;
@synthesize wifi_transport_got_name;
@synthesize wifi_transport_percent;
@synthesize wifi_transport_name;
@synthesize wifi_transport_cell;

//for file locking
@synthesize is_locking_files;

- (void)Disable_Lock_Screen
{
    g_is_lock_screen_disabled_before_file_trans = [UIApplication sharedApplication].idleTimerDisabled;
    [UIApplication sharedApplication].idleTimerDisabled = YES;
}

- (void)Resume_Lock_Screen
{
    [UIApplication sharedApplication].idleTimerDisabled = g_is_lock_screen_disabled_before_file_trans;
}

- (BOOL)is_lock_file
{
    return do_lock_file;
}

- (void)On_Finished_Lock
{
    if (lock_tar && lock_callback)
    {
        [lock_tar performSelector:lock_callback withObject:lock_obj];
    }
    pthread_join(ht_lock, NULL);
    is_locking_files = NO;
    [self start_refresh_file_list];
}

UIImage* get_icon_by_file_type(FILE_TYPE ft)
{
    if (g_icon_array[ft] == 0)
    {
        NSString* path = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], g_icon_img_path[ft]];
        g_icon_array[ft] = [[UIImage alloc] initWithContentsOfFile:path];
        //g_icon_array[ft] = [[[UIImage alloc] initWithContentsOfFile:path] autorelease];
    }
    return g_icon_array[ft];
}

static int got_posted_data(WEB_SERVER_REQUEST_HANDLE hr,long remote_ip,int remote_port,void* param)
{
    unsigned char buf[FILE_IO_BUFFER_LEN] = {0};
    long long read_size = 0;
    long long file_size = 0;
    long long got_size = 0;
    FILE* hf = NULL;
    char cur_dir[MAX_PATH_LEN] = {0};
    char new_file_path[MAX_PATH_LEN] = {0};
	FileListManager* p_flm = (FileListManager*)param;
    
    g_is_transloading_file = YES;
    [p_flm performSelectorOnMainThread:@selector(Disable_Lock_Screen) withObject:nil waitUntilDone:NO];
    
    [NSHomeDirectory() getCString:cur_dir];
    strcat(cur_dir, WIFI_TEMP_PATH);
    p_flm.wifi_transport_got_name = FALSE;
    
    memset(p_flm.wifi_transport_name, 0, MAX_PATH_LEN);
    
    p_flm.wifi_transport_percent = 0.0f;
    
    file_size = web_server_open_post_data(hr);
    
    if (file_size > 0)
    {
        p_flm.wifi_transport_begin = TRUE;
        
        hf = fopen(cur_dir, "wb");
        
        while ((read_size = web_server_read_post_data(hr, buf, FILE_IO_BUFFER_LEN)) > 0)
        {
            fwrite(buf, 1, read_size, hf);
            got_size += read_size;
            p_flm.wifi_transport_percent = ((double)(got_size * 100))/((double)file_size);
            if (!p_flm.wifi_transport_got_name)
            {
                if (web_server_get_post_data_file_name(hr, p_flm.wifi_transport_name, MAX_PATH_LEN) > 0)
                {
                    p_flm.wifi_transport_got_name = TRUE;
                    [NSHomeDirectory() getCString:new_file_path];
                    strcat(new_file_path, FILE_FOLDER);
                    strcat(new_file_path, p_flm.wifi_transport_name);
                }
            }
        }
        
        fclose(hf);
        rename(cur_dir, new_file_path);
        p_flm.wifi_transport_end = TRUE;
    }
    
    web_server_close_post_data(hr);
    
    p_flm.wifi_transport_percent = 100.0f;
    
    [p_flm performSelectorOnMainThread:@selector(Resume_Lock_Screen) withObject:nil waitUntilDone:NO];
    g_is_transloading_file = NO;

}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICE_Table_View_Cell* pcell = [p_list_view cellForRowAtIndexPath:indexPath];
    if (pcell.selected)
    {
        is_deselect = TRUE;
    }
    else
    {
        
    }
    return indexPath;
}

static void cut_path_to_affix(char* path,char* buf)
{
    long l = strlen(path);
    while (l > 0)
    {
        --l;
        if (path[l] == '.')
        {
            break;
        }
    }
    if (l > 0)
    {
        memcpy(buf, path, l);
        buf[l] = 0;
    }
}

static void create_cache_files_path()
{
    char t_dir[MAX_ICE_URL_LEN] = {0};
    DIR* dir;
    //create thumbnail folder
    [NSHomeDirectory() getCString:t_dir];
    strcat(t_dir, THUMBNAIL_FOLDER);
    if (dir = opendir(t_dir))
    {
        closedir(dir);
    }
    else
    {
        mkdir(t_dir, 0777);
    }
    //create movie info folder
    [NSHomeDirectory() getCString:t_dir];
    strcat(t_dir, MOVIE_INFO_FOLDER);
    if (dir = opendir(t_dir))
    {
        closedir(dir);
    }
    else
    {
        mkdir(t_dir, 0777);
    }
}

static void save_cache_files(char* name, int w, int h, long dur)
{
    char t_dir[MAX_ICE_URL_LEN] = {0};
    char t_name[MAX_ICE_URL_LEN] = {0};
    FILE* hf = NULL;
    char tbuf[FILE_IO_BUFFER_LEN] = {0};

    cut_path_to_affix(name, t_name);
    //info
    [NSHomeDirectory() getCString:t_dir];
    strcat(t_dir, MOVIE_INFO_FOLDER);
    strcat(t_dir, t_name);
    strcat(t_dir, MOVIE_INFO_FILE_AFFIX);
    if (hf = fopen(t_dir, "wb"))
    {
        sprintf(tbuf, MOVIE_INFO_FORMAT, w, h, dur);
        fwrite(tbuf, 1, strlen(tbuf), hf);
        fclose(hf);
    }
}

static void delete_cache_files(char* name)
{
    char t_dir[MAX_ICE_URL_LEN] = {0};
    char t_name[MAX_ICE_URL_LEN] = {0};
    FILE* hf = NULL;
    
    cut_path_to_affix(name, t_name);
    //thumbnail
    [NSHomeDirectory() getCString:t_dir];
    strcat(t_dir, THUMBNAIL_FOLDER);
    strcat(t_dir, t_name);
    strcat(t_dir, THUMBNAIL_FILE_AFFIX);
    if (hf = fopen(t_dir,"rb"))
    {
        fclose(hf);
        unlink(t_dir);
    }
    //info
    [NSHomeDirectory() getCString:t_dir];
    strcat(t_dir, MOVIE_INFO_FOLDER);
    strcat(t_dir, t_name);
    strcat(t_dir, MOVIE_INFO_FILE_AFFIX);
    if (hf = fopen(t_dir, "rb"))
    {
        fclose(hf);
        unlink(t_dir);
    }
}

static BOOL try_got_cache_files_info(char* name, char* thumbnail_path, CGFloat* w, CGFloat* h, long* duration_sec)
{
    char t_dir[MAX_ICE_URL_LEN] = {0};
    char t_name[MAX_ICE_URL_LEN] = {0};
    char t_buf[MAX_ICE_STRING_LEN] = {0};
    FILE* hf = NULL;
    
    create_cache_files_path();
    cut_path_to_affix(name, t_name);
    //thumbnail
    [NSHomeDirectory() getCString:t_dir];
    strcat(t_dir, THUMBNAIL_FOLDER);
    strcat(t_dir, t_name);
    strcat(t_dir, THUMBNAIL_FILE_AFFIX);
    if (hf = fopen(t_dir,"rb"))
    {
        strcpy(thumbnail_path, t_dir);
        fclose(hf);
    }
    else
    {
        thumbnail_path[0] = 0;
        //return FALSE;
    }
    //info
    [NSHomeDirectory() getCString:t_dir];
    strcat(t_dir, MOVIE_INFO_FOLDER);
    strcat(t_dir, t_name);
    strcat(t_dir, MOVIE_INFO_FILE_AFFIX);
    if (hf = fopen(t_dir, "rb"))
    {
        fclose(hf);
        NSData* data = [NSData dataWithContentsOfFile:[NSString stringWithCString:t_dir encoding:NSUTF8StringEncoding]];
        int iw = 0, ih = 0, idur = 0;
        //[data getBytes:t_buf length:MAX_ICE_STRING_LEN];
        sscanf([data bytes], MOVIE_INFO_FORMAT, &iw, &ih, &idur);
        *w = (CGFloat)iw;
        *h = (CGFloat)ih;
        *duration_sec = idur;
    }
    else
    {
        *w = 0.f;
        *h = 0.f;
        *duration_sec = 0;
        return FALSE;
    }
    return TRUE;
}

- (void)Got_Movie_Info_CallBack
{
    BGView* bg_v = [BGView get_Last_BG_view];
    UIImage* t_img = nil;
    char t_name[MAX_ICE_URL_LEN] = {0};
    int len = 0;
    MOVIE_INFO mi = [Player_Model current_Movie_Info];
    [mi.thumbnail_path getCString:t_name maxLength:MAX_ICE_URL_LEN encoding:NSUTF8StringEncoding];
    len = strlen(t_name);
    while (len > 0)
    {
        --len;
        if (t_name[len] == '/' || t_name[len] == '\\')
        {
            ++len;
            break;
        }
    }
    if (mi.duration_in_seconds > 0)
    {
        save_cache_files(&t_name[len], mi.width, mi.height, mi.duration_in_seconds);
    }
    [mi.movie_path getCString:t_name maxLength:MAX_ICE_URL_LEN encoding:NSUTF8StringEncoding];
    if (strcmp(t_name, selected_file_name) == 0)
    {
        if (mi.thumbnail_path)
        {
            t_img = [UIImage imageWithContentsOfFile:mi.thumbnail_path];
        }
        else
        {
            t_img = [UIImage imageNamed:@"bg_logo.png"];
        }
        bg_v.low_wnd.p_preview.image = t_img;
        if (mi.width > 0)
        {
            bg_v.low_wnd.p_label_file_size_val.text = [NSString stringWithFormat:@"%dX%d",(NSInteger)mi.width,(NSInteger)mi.height];
        }
        else
        {
            bg_v.low_wnd.p_label_file_size_val.text = @UNKNOWN_FRAME_SIZE;
        }
        if (mi.duration_in_seconds > 0)
        {
            bg_v.low_wnd.p_label_duration_val.text = [NSString stringWithFormat:@"%i:%02i:%02i", mi.duration_in_seconds/3600, (mi.duration_in_seconds%3600)/60, mi.duration_in_seconds%60];
        }
        else
        {
            bg_v.low_wnd.p_label_duration_val.text = @UNKNOWN_DURATION;
        }
    }
}

- (void)Load_Movie_Info_To_Low_Wnd:(char*)url file_name:(char*)name
{
    BGView* bg_v = [BGView get_Last_BG_view];
    FILE_TYPE ft = get_file_type_by_file_name(name);
    UIImage* t_img = nil;
    CGSize size = {0};
    long duration = 0;
    char thumbnail_path[MAX_ICE_URL_LEN] = {0};
    char t_name[MAX_ICE_URL_LEN] = {0};
    switch (ft)
    {
        case F_T_VIDEO:
        case F_T_AUDIO:
            if (try_got_cache_files_info(name,thumbnail_path,&size.width,&size.height,&duration))
            {
                if (ft == F_T_VIDEO)
                {
                    t_img = [UIImage imageWithContentsOfFile:[NSString stringWithCString:thumbnail_path encoding:NSUTF8StringEncoding]];
                    bg_v.low_wnd.p_preview.image = t_img;
                    bg_v.low_wnd.p_label_file_size_val.text = [NSString stringWithFormat:@"%dX%d",(NSInteger)size.width,(NSInteger)size.height];
                }
                else
                {
                    t_img = [UIImage imageNamed:@"bg_logo.png"];
                    bg_v.low_wnd.p_preview.image = t_img;
                    bg_v.low_wnd.p_label_file_size_val.text = @UNKNOWN_FRAME_SIZE;
                }
                bg_v.low_wnd.p_label_duration_val.text = [NSString stringWithFormat:@"%i:%02i:%02i", duration/3600, (duration%3600)/60, duration%60];
            }
            else
            {
                cut_path_to_affix(name, t_name);
                [NSHomeDirectory() getCString:thumbnail_path];
                strcat(thumbnail_path, THUMBNAIL_FOLDER);
                strcat(thumbnail_path, t_name);
                strcat(thumbnail_path, THUMBNAIL_FILE_AFFIX);
                CGRect rect = bg_v.low_wnd.p_preview.bounds;
                NSInteger w = (NSInteger)rect.size.width;
                NSInteger h = (NSInteger)rect.size.height;
                strcpy(selected_file_name, url);
                [Player_Model get_Movie_Info:[NSString stringWithCString:url encoding:NSUTF8StringEncoding] thumbnail_path:[NSString stringWithCString:thumbnail_path encoding:NSUTF8StringEncoding] thumbnail_width:w thumbnail_height:h thumbnail_time_at:DEFAULT_THUMBNAIL_TIME target:self got_info_callback:@selector(Got_Movie_Info_CallBack) withObject:nil];
                t_img = [UIImage imageNamed:@"bg_logo.png"];
                bg_v.low_wnd.p_preview.image = t_img;
                bg_v.low_wnd.p_label_file_size_val.text = @UNKNOWN_FRAME_SIZE;
                bg_v.low_wnd.p_label_duration_val.text = @UNKNOWN_DURATION;
            }
            break;
        case F_T_PICTURE:
            t_img = [UIImage imageWithContentsOfFile:[NSString stringWithCString:url encoding:NSUTF8StringEncoding]];
            size = t_img.size;
            bg_v.low_wnd.p_preview.image = t_img;
            bg_v.low_wnd.p_label_file_size_val.text = [NSString stringWithFormat:@"%dX%d",(NSInteger)size.width,(NSInteger)size.height];
            bg_v.low_wnd.p_label_duration_val.text = @UNKNOWN_DURATION;
            break;
        default:
            t_img = [UIImage imageNamed:@"bg_logo.png"];
            bg_v.low_wnd.p_preview.image = t_img;
            bg_v.low_wnd.p_label_file_size_val.text = @UNKNOWN_FRAME_SIZE;
            bg_v.low_wnd.p_label_duration_val.text = @UNKNOWN_DURATION;
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //prevent from deselection scrolling bugs
    //[self.navigationController dismissModalViewControllerAnimated:YES];
    
    BGView* bg_v = [BGView get_Last_BG_view];
    
    if (is_deselect)
    {
        if (bg_v)
        {
            [bg_v On_Leave_Low_Wnd];
        }
        [tableView deselectRowAtIndexPath:indexPath animated:FALSE];
        is_deselect = FALSE;
    }
    else
    {
        FileList_Cell* pcell = [p_list_view cellForRowAtIndexPath:indexPath];
        char url[MAX_ICE_URL_LEN] = {0};
        char name[MAX_ICE_URL_LEN] = {0};
        
        if (bg_v)
        {
            [NSHomeDirectory() getCString:url];
            strcat(url, FILE_FOLDER);
            [pcell.file_name.text getCString:(&url[strlen(url)]) maxLength:(MAX_ICE_URL_LEN - strlen(url)) encoding:NSUTF8StringEncoding];
            [pcell.file_name.text getCString:name maxLength:MAX_ICE_URL_LEN encoding:NSUTF8StringEncoding];
            [self Load_Movie_Info_To_Low_Wnd:url file_name:name];
            [bg_v On_Show_Low_Wnd:url];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (file_list == NULL)
    {
        [self refresh_file_list];
    }
	return wifi_transport_is_doing ? (file_list->count + 1) :file_list->count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FileList_Cell *cell = (FileList_Cell*)[tableView dequeueReusableCellWithIdentifier:p_cell_id];
    if (cell == nil)
    {
        // Create a temporary UIViewController to instantiate the custom cell.
        UITableViewController *temporaryController = [[UIViewController alloc] initWithNibName:p_cell_id bundle:nil];
        // Grab a pointer to the custom cell.
        cell = (FileList_Cell *)temporaryController.view;
        // Release the temporary UIViewController.
        [temporaryController release];
    }
    NSUInteger it[2] = {0};
    [indexPath getIndexes:it];
    FILE_TYPE ft = F_T_OTHER;
    
    /*if (cell.file_name.text)
    {
        [cell.file_name release];
        cell.file_name.text = nil;
    }*/
    
    if (wifi_transport_is_doing && it[1] >= file_list->count)
    {
        char percent_str[64] = {0};
        wifi_transport_cell = cell;
        wifi_transport_cell.file_icon.image = get_icon_by_file_type(F_T_OTHER);
        wifi_transport_cell.play_btn.hidden = TRUE;
        sprintf(percent_str, "%.1f%%", wifi_transport_percent);
        wifi_transport_cell.play_label.text = [[[NSString alloc]initWithCString:percent_str encoding:NSUTF8StringEncoding]autorelease];
    }
    else
    {
        cell.file_name.text = [[[NSString alloc]initWithCString:file_list->array[it[1]].file_name encoding:NSUTF8StringEncoding]autorelease];
        ft = get_file_type_by_file_name(file_list->array[it[1]].file_name);
        cell.file_icon.image = get_icon_by_file_type(ft);
        if (ft == F_T_VIDEO || ft == F_T_AUDIO)
        {
            cell.play_btn.hidden = FALSE;
            cell.play_label.text = IGS(EG_STR_ID_LIST_CELL_PLAY);
        }
        else
        {
            cell.play_btn.hidden = TRUE;
            cell.play_label.text = @"";
        }
        
    }
    
    
    return cell;
}

- (id)initWithCoder:(NSCoder *)aDecoder; 
{
    //printf("YOOOOOOO!\n");
    file_list = NULL;
    cur_dir = NULL;
    refresh_timer = NULL;
    
    wifi_file_name = NULL;
    wifi_file_size = 0;
    wifi_file_transported_size = 0;
    
    html_instead_pos = 0;
    
    lock_tar = NULL;
    lock_callback = NULL;
    lock_obj = NULL;
	
	
	wifi_transport_begin = FALSE;
	wifi_transport_end = FALSE;
	wifi_transport_is_doing = FALSE;
	wifi_transport_got_name = FALSE;
	wifi_transport_percent = 0.0f;
	wifi_transport_name = malloc(MAX_PATH_LEN);
	memset(wifi_transport_name, 0, MAX_PATH_LEN);
	wifi_transport_cell = NULL;
    
    is_deselect = FALSE;
    
    selected_file_name = malloc(MAX_PATH_LEN);
    memset(selected_file_name, 0, MAX_PATH_LEN);
    
    [self start_refresh_file_list];
	
	id ret_val = [super initWithCoder:aDecoder]; 
	
    web_server_set_request_callback_func(WS_RM_POST, "", got_posted_data,(void*)self);
    
	return ret_val;
}

- (void)create_file_list
{
    if (cur_dir == NULL)
    {
        cur_dir = (char*)malloc(MAX_PATH_LEN);
        [NSHomeDirectory() getCString:cur_dir];
		strcat(cur_dir, FILE_FOLDER);
    }
    file_list = create_file_list(cur_dir);
    g_current_file_list = file_list;
}

- (void)refresh_file_list
{
    BOOL file_has_modified = FALSE;
    int old_count = 0;
    
    char *t_ip = NULL;
    int ip_count = 0;
    
    char xml_prefix[LOCAL_WEB_SERVER_LEN];
    char xml_path[MAX_PATH_LEN];
    
    if (file_list == NULL)
    {
        [self create_file_list];
        file_has_modified = TRUE;
    }
    old_count = file_list->count;
    update_file_list(file_list);
    if (old_count != file_list->count)
    {
        file_has_modified = TRUE;
    }
    if (wifi_transport_begin)
    {
        file_has_modified = TRUE;
        wifi_transport_begin = FALSE;
        wifi_transport_is_doing = TRUE;
    }
    if (wifi_transport_end)
    {
        file_has_modified = TRUE;
        wifi_transport_end = FALSE;
        wifi_transport_is_doing = FALSE;
        wifi_transport_cell = NULL;
    }
    if (wifi_transport_is_doing && wifi_transport_cell)
    {
        char percent_str[64] = {0};
        sprintf(percent_str, "%.1f%%", wifi_transport_percent);
        wifi_transport_cell.play_label.text = [[[NSString alloc]initWithCString:percent_str encoding:NSUTF8StringEncoding]autorelease];
        if (wifi_transport_got_name)
        {
            wifi_transport_cell.file_name.text = [[[NSString alloc]initWithCString:wifi_transport_name encoding:NSUTF8StringEncoding]autorelease];
        }
    }
    if (file_has_modified)
    {
        //refresh table list view
        [p_list_view reloadData];
        //refresh file list xml for web browser's AJAX
        [NSHomeDirectory() getCString:xml_path];
        strcat(xml_path, WEB_FOLDER);
        strcat(xml_path, STR_FILE_DIR_XML);
        sprintf(xml_prefix, "/%s/", WEB_REDIR_SYMBOL);
        make_file_list_xml(xml_path, file_list, xml_prefix);
    }
    
    //refresh ip address,(including html post address).
    ip_count = web_server_get_local_ip_address_count();
    if (ip_count > 1)
    {
        t_ip = web_server_get_local_ip_address(web_server_get_server_ip_idx(g_web_server_handle));
        if (strcmp(t_ip, g_cur_ip))
        {
            strcpy(g_cur_ip, t_ip);
            sprintf(g_web_server_url, "http://%s:%s/", g_cur_ip, DEFAULT_WEB_SERVER_PORT);
        }
    }
    
    if (g_has_export_new_file)
    {
        g_has_export_new_file = false;
        [[BGView get_Last_BG_view] On_Call_Player_View:g_exported_new_file];
    }
}

- (void)start_refresh_file_list
{
    if (refresh_timer)
    {
        [refresh_timer invalidate];
        [refresh_timer release];
        refresh_timer = NULL;
    }
    [self refresh_file_list];
    refresh_timer = [[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(refresh_file_list) userInfo:nil repeats:YES] retain];
}

- (void)stop_refresh_file_list
{
    if (refresh_timer)
    {
        [refresh_timer invalidate];
        [refresh_timer release];
        refresh_timer = NULL;
    }
}

- (void)delete_selected_file
{
    FileList_Cell* pcell = [p_list_view cellForRowAtIndexPath:[p_list_view indexPathForSelectedRow]];
    char cur_dir[MAX_PATH_LEN] = {0};
    [NSHomeDirectory() getCString:cur_dir];
    strcat(cur_dir, FILE_FOLDER);
    [pcell.file_name.text getCString:&cur_dir[strlen(cur_dir)] maxLength:(MAX_PATH_LEN - strlen(cur_dir)) encoding:NSUTF8StringEncoding];
    unlink(cur_dir);
    //delete reference cache files
    [pcell.file_name.text getCString:cur_dir maxLength:MAX_PATH_LEN encoding:NSUTF8StringEncoding];
    FILE_TYPE ft = get_file_type_by_file_name(cur_dir);
    switch (ft)
    {
        case F_T_VIDEO:
        case F_T_AUDIO:
            delete_cache_files(cur_dir);
            break;
        default:
            break;
    }
    [self refresh_file_list];
}

static void* dir_lock_thread(void* p)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
                               
    FileListManager* pmgr = (FileListManager*)p;
    BOOL succeed = NO;
    char ducument[MAX_ICE_URL_LEN] = {0};
    [NSHomeDirectory() getCString:ducument];
    strcat(ducument, FILE_FOLDER);
    
    succeed = lock_dir(ducument, [pmgr is_lock_file]);
    
    [pmgr performSelectorOnMainThread:@selector(On_Finished_Lock) withObject:nil waitUntilDone:NO];
    
    [pool release];
    return NULL;
}

- (void)start_lock_files:(BOOL)is_lock target:(id)target call_back:(SEL)end_notify parameter:(id)obj
{
    lock_tar = target;
    lock_callback = end_notify;
    lock_obj = obj;
    do_lock_file = is_lock;
    is_locking_files = YES;
    [self stop_refresh_file_list];
    pthread_create(&ht_lock, NULL, dir_lock_thread, (void*)self);
}

- (void)dealloc
{
    if (cur_dir)
    {
        free(cur_dir);
    }
    if (file_list)
    {
        g_current_file_list = NULL;
        close_file_list(file_list);
    }
	if (wifi_transport_name)
	{
		free(wifi_transport_name);
		wifi_transport_name = NULL;
	}
    if (refresh_timer)
    {
        [refresh_timer invalidate];
        [refresh_timer release];
        refresh_timer = NULL;
    }
    if (selected_file_name)
    {
        free(selected_file_name);
        selected_file_name = NULL;
    }
    [super dealloc];
}

- (void)create_SubViews:(UIViewController*)controller
{
    [super create_SubViews:controller];
}

- (void)destroy_SubViews
{
}

@end


static BOOL create_a_path(char* path)
{
    char t_dir[MAX_ICE_URL_LEN] = {0};
    DIR* dir;
    strcpy(t_dir, path);
    if (dir = opendir(t_dir))
    {
        closedir(dir);
        return TRUE;
    }
    else
    {
        mkdir(t_dir, 0777);
    }
    
    if (dir = opendir(t_dir))
    {
        closedir(dir);
        return TRUE;
    }
    
    return FALSE;
}

static BOOL lock_dir(char* dir, BOOL is_lock)
{
    char dir_buf[MAX_ICE_URL_LEN] = {0};
    char lock_dir_buf[MAX_ICE_URL_LEN] = {0};
    char* lock_name = NULL;
    char* name = NULL;
    int len = 0;
    FILE_INFO_LIST *lst = NULL;
    int i = 0;
    
    strcpy(dir_buf, dir);
    len = strlen(dir_buf);
    if (dir_buf[len - 1] != '/' && dir_buf[len - 1] != '\\')
    {
        dir_buf[len] = '/';
    }
    
    strcpy(lock_dir_buf, dir_buf);
    strcat(lock_dir_buf, LOCKED_FOLDER_NAME);
    
    name = &dir_buf[strlen(dir_buf)];
    lock_name = &lock_dir_buf[strlen(lock_dir_buf)];
    
    if(!create_a_path(lock_dir_buf))
    {
        goto FAILED;
    }
    
    if (is_lock)
    {
        lst = create_file_list(dir_buf);
    }
    else
    {
        lst = create_file_list(lock_dir_buf);
    }
    
    if (lst)
    {
        for (i = 0; i < lst->count; ++i)
        {
            strcpy(name, lst->array[i].file_name);
            strcpy(lock_name, lst->array[i].file_name);
            if (is_lock)
            {
                rename(dir_buf, lock_dir_buf);
            }
            else
            {
                rename(lock_dir_buf, dir_buf);
            }
            
        }
        close_file_list(lst);
        lst = NULL;
    }
    else
    {
        goto FAILED;
    }
    
    return YES;
FAILED:
    if (lst)
    {
        close_file_list(lst);
        lst = NULL;
    }
    return NO;
}

